package com.shty.wd.utils.module.Australia;

import com.shty.wd.utils.module.IOTools.IOUtil;
import com.shty.wd.utils.module.related.Entity;
import com.shty.wd.utils.module.related.JsonParse;
import com.shty.wd.utils.module.related.ResultData;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * author: TAOPENG
 * time ： 2017/11/10
 **/
public class RelationAnalysis {
    public static final String CANADA_LOCATION = "Australia/location.txt";
    public static final String CANADA_ORG = "Australia/organization.txt";
    public static final String CANADA_NAME = "Australia/name.txt";

    public static String DIC_LOCATION = "";
    public static String DIC_NAME = "";
    public static String DIC_ORG = "";

    public static void init() {
        if (DIC_LOCATION.length() == 0) {
            DIC_LOCATION = IOUtil.loadSource(CANADA_LOCATION);
        }
//            if (DIC_NAME.length() == 0) {
//                DIC_NAME = IOUtil.loadSource(CANADA_NAME);
//            }
        if (DIC_ORG.length() == 0) {
            DIC_ORG = IOUtil.loadSource(CANADA_ORG);
        }
    }

    /**
     * 通过josn字符串判断是否涉及Australia
     *
     * @param data 传入的json字符串
     * @return 返回结果
     */
    public static String analyzeRelationsWithString(String data) {
        init();
        List<Entity> flist;
        ResultData resultJson;
        // parsing search results
        try {
            JsonParse jsonParse = new JsonParse();
            resultJson = jsonParse.parse(data);
            flist = resultJson.getFriendsList();
        } catch (Exception e) {
            return "-1";
        }

        // analyze whether the friends are related to China
        try {
            analysis(flist);
        } catch (Exception e) {
            return "-3";
        }
        // transform the analysis results into strings
        return resultJson.creatJSON();
    }

    /**
     * 通过josn字符串判断是否涉及Australia
     *
     * @param dirPath 资料存放的文件夹
     * @return 返回结果
     */
    public static String analyzeRelationsWithDir(String dirPath) {
        init();
        List<Entity> flist;
        List<ResultData> resultJson;
        StringBuffer result = new StringBuffer();
        // parsing search results

        JsonParse jsonParse = new JsonParse();
        resultJson = jsonParse.parseFormDir(dirPath);
        for (ResultData json : resultJson) {
            flist = json.getFriendsList();
            // analyze whether the friends are related to China
            analysis(flist);
            // transform the analysis results into strings
            result.append(json.creatJSON()).append("\n");
        }
        return result.toString();
    }

    public static String analyzeRelations(String jsonData) {
        init();
        JSONArray array = JSONArray.fromObject(jsonData);
        JsonParse jsonParse = new JsonParse();
        List<Entity> list = jsonParse.getEntityList(array);
        analysis(list);
        return JSONArray.fromObject(list).toString();
    }

    // analyze whether the friends are related to China
    private static void analysis(List<Entity> list) {
        for (Entity aList : list) {
            CheckRelation(aList);
        }
    }

    // analyze one friend
    public static void CheckRelation(Entity en) {
        Map<String, String> result = en.getResult();
        StringBuffer basis = new StringBuffer();
        for (Map.Entry<String, String> entry : result.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();

            if (key.contains("url")) continue;
            if (key.contains("id")) continue;
            if (key.contains("name")) continue;

            // analyze the relation based on the following rules
            boolean has1 = false;
            String location = checkLocationRelation(value);
            if (!StringUtils.isEmpty(location))
                has1 = true;

            boolean has2 = false;
            String org = checkOrgRelation(value);
            if (!StringUtils.isEmpty(org))
                has2 = true;

            // store the proofs for the relations
            if (has1 || has2) {
                en.setHasRelations(true);
                basis.append(key).append(":");

                if (has1) {
                    basis.append(location).append(", ");
                }
                if (has2) {
                    basis.append(org).append(", ");
                }
            }
        }
        en.setBasis(basis.toString());
    }

    //Check locations in the dictionary.
    public static String checkLocationRelation(String location) {

        if (DIC_LOCATION.length() == 0) {
            return null;
        }
        String newlocation = location.toLowerCase();
        String reg = "([^a-zA-Z\\u4e00-\\u9fa5]|^)(" + DIC_LOCATION + ")([^a-zA-Z\\u4e00-\\u9fa5]|$)";
        Pattern myPattern = Pattern.compile(reg);
        Matcher myMatcher = myPattern.matcher(newlocation);
        if (myMatcher.find()) {
            if (myMatcher.group(2).trim().length() > 0) {
                return getOriginStr(newlocation, location, myMatcher.group(2).trim());
            }
        }
        return null;
    }

    // Check organizations in the dictionary.
    public static String checkOrgRelation(String organization) {

        if (DIC_ORG.length() == 0) {
            return null;
        }
        String newOrganization = organization.toLowerCase();
        String reg = "([^a-zA-Z\\u4e00-\\u9fa5]|^)(" + DIC_ORG + ")([^a-zA-Z\\u4e00-\\u9fa5]|$)";
        Pattern myPattern = Pattern.compile(reg);
        Matcher myMatcher = myPattern.matcher(newOrganization);
        if (myMatcher.find()) {
            if (myMatcher.group(2).trim().length() > 0) {
                return getOriginStr(newOrganization, organization, myMatcher.group(2).trim());
            }
        }
        return null;
    }

    public static String getOriginStr(String newStr, String oldStr, String pattern) {
        int start = newStr.indexOf(pattern, 0);
        int end = start + pattern.length();
        return oldStr.substring(start, end);
    }
}
